using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using System.Text;
using System.Collections.Generic;

namespace ZGL.Api.Controllers
{
    [ApiController]
    [Route("api/mockserialport")]
    public class MockSerialPortController : ControllerBase
    {
        private static readonly Dictionary<string, byte[]> _mockResponses = new Dictionary<string, byte[]>
        {
            // 模拟版本查询响应
            ["version"] = new byte[] { 0xFE, 0xFE, 0xFE, 0x68, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A },
            
            // 模拟环境数据响应
            ["environment"] = new byte[] { 0xFE, 0xFE, 0xFE, 0x68, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29 },
            
            // 模拟控制命令响应
            ["control"] = new byte[] { 0xFE, 0xFE, 0xFE, 0x68, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 }
        };

        private static readonly Random _random = new Random();

        /// <summary>
        /// 模拟发送数据到COM3
        /// </summary>
        [HttpPost("send")]
        public async Task<IActionResult> SendData([FromBody] byte[] data)
        {
            try
            {
                // 模拟发送延迟
                await Task.Delay(100);

                // 记录发送的数据
                Console.WriteLine($"COM3发送数据: {BitConverter.ToString(data)}");

                return Ok(new
                {
                    Success = true,
                    Message = "数据已发送到COM3",
                    Timestamp = DateTime.Now,
                    Data = BitConverter.ToString(data)
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Error = ex.Message });
            }
        }

        /// <summary>
        /// 模拟从COM4接收数据
        /// </summary>
        [HttpGet("receive")]
        public async Task<IActionResult> ReceiveData([FromQuery] int timeout = 1000)
        {
            try
            {
                // 模拟接收延迟
                await Task.Delay(100);

                // 随机选择一个模拟响应
                var responseTypes = new[] { "version", "environment", "control" };
                var responseType = responseTypes[_random.Next(responseTypes.Length)];
                var responseData = _mockResponses[responseType];

                Console.WriteLine($"COM4接收数据: {BitConverter.ToString(responseData)}");

                return Ok(new
                {
                    Success = true,
                    Message = "从COM4接收到数据",
                    Timestamp = DateTime.Now,
                    Data = BitConverter.ToString(responseData),
                    ResponseType = responseType
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Error = ex.Message });
            }
        }

        /// <summary>
        /// 模拟发送并接收数据
        /// </summary>
        [HttpPost("sendandreceive")]
        public async Task<IActionResult> SendAndReceive([FromBody] byte[] data, [FromQuery] int timeout = 1000)
        {
            try
            {
                // 模拟发送延迟
                await Task.Delay(100);
                Console.WriteLine($"COM3发送数据: {BitConverter.ToString(data)}");

                // 模拟接收延迟
                await Task.Delay(100);

                // 根据发送的数据类型返回对应的响应
                byte[] responseData;
                if (data[6] == 0x31) // 版本查询
                {
                    responseData = _mockResponses["version"];
                }
                else if (data[6] == 0x32) // 环境数据
                {
                    responseData = _mockResponses["environment"];
                }
                else // 控制命令
                {
                    responseData = _mockResponses["control"];
                }

                Console.WriteLine($"COM4接收数据: {BitConverter.ToString(responseData)}");

                return Ok(new
                {
                    Success = true,
                    Message = "发送并接收数据成功",
                    Timestamp = DateTime.Now,
                    SentData = BitConverter.ToString(data),
                    ReceivedData = BitConverter.ToString(responseData)
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Error = ex.Message });
            }
        }

        /// <summary>
        /// 获取模拟端口状态
        /// </summary>
        [HttpGet("status")]
        public IActionResult GetPortStatus()
        {
            return Ok(new
            {
                COM3Status = "Open",
                COM4Status = "Open",
                Timestamp = DateTime.Now
            });
        }
    }
} 